// examples/custom_snapshotter.go
// 自定义 snapshotter 使用示例

package examples

import (
	"context"
	"fmt"
	"log"

	"github.com/containerd/containerd/v2/core/snapshots"
	"github.com/onyx/snapshotter/pkg/config"
	"github.com/onyx/snapshotter/pkg/service"
)

func ExampleCustomSnapshotter() error {
	// 创建配置
	cfg := &config.Config{
		Root:      "/var/lib/custom-snapshotter",
		ChunkSize: 8 * 1024 * 1024, // 8MB chunks
		DBBackend: "pebble",
	}

	// 创建 snapshotter
	snapshotter, err := service.NewSnapshotter(cfg)
	if err != nil {
		return fmt.Errorf("failed to create snapshotter: %w", err)
	}
	defer snapshotter.Close()

	ctx := context.Background()

	// Prepare 一个新快照
	key := "my-snapshot"
	mounts, err := snapshotter.Prepare(ctx, key, "")
	if err != nil {
		return fmt.Errorf("prepare failed: %w", err)
	}

	log.Printf("Prepared snapshot with mounts: %v", mounts)

	// 检查快照状态
	info, err := snapshotter.Stat(ctx, key)
	if err != nil {
		return fmt.Errorf("stat failed: %w", err)
	}

	log.Printf("Snapshot info: Key=%s, Kind=%d, Readonly=%v",
		info.Name, info.Kind, info.Readonly)

	// 提交快照
	commitName := "my-snapshot-committed"
	if err := snapshotter.Commit(ctx, commitName, key); err != nil {
		return fmt.Errorf("commit failed: %w", err)
	}

	log.Printf("Committed snapshot as %s", commitName)

	// 遍历快照
	err = snapshotter.Walk(ctx, func(ctx context.Context, info snapshots.Info) error {
		log.Printf("Found snapshot: %s (kind=%d)", info.Name, info.Kind)
		return nil
	})
	if err != nil {
		return fmt.Errorf("walk failed: %w", err)
	}

	// 删除快照
	if err := snapshotter.Remove(ctx, commitName); err != nil {
		return fmt.Errorf("remove failed: %w", err)
	}

	log.Println("Snapshot removed successfully")
	return nil
}

// ---
